package org.rssReader;


import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.rssReader.model.Model;

public class SettingsReader {
	static Element root;
	private Model model;
	private static final Logger logger = Logger.getLogger(SettingsReader.class);
	public SettingsReader(String filePath) throws JDOMException, IOException {
		SAXBuilder builder = new SAXBuilder(false);
		Document doc = builder.build(new File(filePath));
		root = doc.getRootElement();
		model = Model.getInstance();
	}
	
	/**
	 * parse the settings.xml file to get the wanted shows
	 */
	@SuppressWarnings("unchecked")
	public void getShwos(){
	try{
		List shows = root.getChild("shows").getChildren();
		Iterator i = shows.iterator();
		while(i.hasNext()){
			Element show = (Element)i.next();
			// get the series name
			String showName = show.getChild("name").getText();
			// transfer the name into feeds name. I.e - "how I met your mother" => "how.I.met.your.mother"
			showName =  showName.replaceAll(" ", ".");
			// get the wanted series
			String showSeries = show.getChild("series").getText();
			// pad the series with 0 if needed
			//showSeries = (showSeries.length() <2)?	"0"+showSeries : showSeries;
			showSeries = (showSeries.length() == 1)?String.format("%01d", showSeries):showSeries;
			model.AddShow(showName+ ".S" + showSeries);
		}
		List servers = root.getChild("servers").getChildren();
		i = servers.iterator();
		while(i.hasNext()){
			Element server = (Element)i.next();
			model.AddServer(server.getChild("name").getText());
		}
	}
	catch (Exception e) {
	     logger.error("Error in getShows", e);
	    }
	}

}
